package com.ysu.concurrency.thread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * 测试使用ForkJoin实现求和计算任务
 * 3000 for
 * 6000 ForkJoin
 * 9000 （Stream 并行流）
 * */
public class TestForkJoin extends RecursiveTask<Long> {
    private Long strat; //1
    private Long end;   //999999

    //临界值
    private Long temp = 10000L;

    public TestForkJoin(Long strat, Long end) {
        this.strat = strat;
        this.end = end;
    }


    //计算方法
    @Override
    protected Long compute() {
        if((end - strat) < temp){
            Long sum = 0L;
            for (long i = strat; i <= end; i++) {
                sum+=1;
            }
            return sum;
        }else {
            //forkjoin 分支合并计算
            long  middle = (strat + end) / 2; //取中间值
            TestForkJoin testForkJoin1 = new TestForkJoin(strat, middle); //拆分任务
            TestForkJoin testForkJoin2 = new TestForkJoin(middle+1, end);
            testForkJoin1.fork(); //把任务压入队列
            testForkJoin2.fork();

            return testForkJoin1.join() + testForkJoin2.join(); //将结果合并
        }
    }

    public static void main(String[] args) {
        test1();
        try {
            test2();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        test3();
    }

    public static void test1(){
        long start = System.currentTimeMillis();
        long sum = 0L;
        for (long i = 0; i <= 10_0000_0000L; i++){
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("普通循环统计用时 " + (end-start));
    }

    //使用forkjoin
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new TestForkJoin(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task); //提交任务 有返回值
        Long sum = submit.get();

        long end = System.currentTimeMillis();
        System.out.println("ForkJoin统计用时 " + (end-start));
    }
    //使用stream并行流
    public static void test3(){
        long start = System.currentTimeMillis();
        LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("stream并行流统计用时 " + (end-start));
    }

}
